package one.stand.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.vioao.wechat.api.CustomServiceApi;
import com.github.vioao.wechat.bean.entity.message.msg.LinkMessage;
import com.github.vioao.wechat.bean.response.BaseResponse;
import com.jmp.base.dto.AccountAppIdRequest;
import com.jmp.base.dto.AccountResponse;
import com.jmp.base.dto.WechatTokenRequest;
import com.jmp.base.dto.WechatTokenResponse;
import com.jmp.feign.AccountFeign;
import com.jmp.feign.WechatFeign;
import com.jmp.feign.WechatServiceFegin;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.model.ResultModel;
import one.stand.model.SysDictValue;
import one.stand.request.ComponentProgramRequest;
import one.stand.request.ComponentVerifyTicketRequest;
import one.stand.service.sys.SysDictValueService;
import one.stand.util.AssertUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

/**
 * @author: QIK
 * @CreateDate: 2019/5/9 14:33
 */
@RestController
@RequestMapping("wechatApi/wx")
@Slf4j
public class WxController {
    @Autowired
    private WechatFeign wechatFeign;
    @Autowired
    private WechatServiceFegin wechatServiceFegin;
    @Autowired
    private AccountFeign accountFeign;
    @Autowired
    private SysDictValueService sysDictValueService;

    /**
     * 小程序客服推送验证，自动回复.
     */
    @ApiOperation(value = "小程序消息推送")
    @GetMapping("msg/{appId}")
    public void msg(HttpServletRequest request
            , HttpServletResponse response
            , @PathVariable("appId") String appId
    ) throws IOException {
        if (request.getParameterMap().containsKey("echostr")) {
            response.getWriter().write(request.getParameter("echostr"));
            return;
        }
    }

    /**
     * 小程序客服推送验证，自动回复.
     *
     * @param response
     * @param appId
     * @param msg      消息json
     * @throws IOException
     */
    @ApiOperation(value = "小程序消息推送")
    @PostMapping("msg/{appId}")
    public void msg(HttpServletResponse response
            , @PathVariable("appId") String appId
            , @RequestBody Map<String, Object> msg
    ) throws IOException {
        AccountAppIdRequest accountAppIdRequest = AccountAppIdRequest.builder().appId(appId).build();
        ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getByAppId(accountAppIdRequest);
        AssertUtil.isTrue(accountResponseResultModel);

        String companyKey = accountResponseResultModel.getData().getCompanyKey();
        String secret = accountResponseResultModel.getData().getAppSecret();

        Map<String, SysDictValue> dictValueMap = sysDictValueService.getMapNullDefault(SysDictValueService.Type.WX_KF, companyKey);
        AssertUtil.nonNull(dictValueMap, "配置未开启");
        SysDictValue appDownLoadDict = dictValueMap.get(SysDictValueService.TypeNameWxKf.APP_DOWNLOAD_URL.name());
        SysDictValue messageDict = dictValueMap.get(SysDictValueService.TypeNameWxKf.MESSAGE.name());

//        if ("miniprogrampage".equals(msg.get("MsgType"))) {
        WechatTokenRequest tokenRequest = WechatTokenRequest.builder()
                .appId(appId)
                .appSecret(secret)
                .build();
        ResultModel<WechatTokenResponse> responseResultModel = wechatFeign.token(tokenRequest);
        AssertUtil.isTrue(responseResultModel);

        //LinkMessage
        LinkMessage.Link link = new LinkMessage.Link();
        link.setTitle(messageDict.getValue());
        link.setDescription(messageDict.getMemo());
        link.setUrl(appDownLoadDict.getValue());
        link.setThumb_url(appDownLoadDict.getMemo());
        String touser = MapUtils.getString(msg, "FromUserName");
        LinkMessage linkMessage = new LinkMessage(touser, link);
        log.info("请求参数={}", JSONObject.toJSONString(linkMessage));

        BaseResponse baseResponse = CustomServiceApi.sendMsg(responseResultModel.getData().getToken(), linkMessage);
        log.info("自动回复结果={}", JSONObject.toJSONString(baseResponse));
//        }
        response.getWriter().write("success");
    }

    @ApiOperation(value = "增加微信模版")
    @GetMapping("addTemplate")
    public ResultModel addTemplat(String appId) {
        log.info("#增加微信模版appid={}", appId);
        return wechatServiceFegin.addTemplate(appId);
    }

    @RequestMapping("wxcallback/{appid}")
    public String wxcallback(@PathVariable("appid") String appid, HttpServletRequest httpServletRequest, ComponentVerifyTicketRequest request) {
        Map<String, String[]> data = httpServletRequest.getParameterMap();
        log.info("回调参数ticket:{}", JSON.toJSONString(data));
        StringBuffer inputString = new StringBuffer();
        try {
            BufferedReader reader = httpServletRequest.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            httpServletRequest.getReader().close();
            log.info("微信回调流ticket：{}", inputString.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAppid(appid);
        request.setXml(inputString.toString());
        return wechatServiceFegin.wxcallback(request);
    }


    @RequestMapping("program/{appid}")
    public String program(@PathVariable("appid") String appid, HttpServletRequest httpServletRequest, ComponentProgramRequest request) {
        Map<String, String[]> data = httpServletRequest.getParameterMap();
        log.info("回调参数program:{}", JSON.toJSONString(data));
        StringBuffer inputString = new StringBuffer();
        try {
            BufferedReader reader = httpServletRequest.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            httpServletRequest.getReader().close();
            log.info("微信回调流program：{}", inputString.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setAppid(appid);
        request.setXml(inputString.toString());
        return wechatServiceFegin.program(request);
    }
}
